package org.onvivals.app.ai.tts.model.minimax;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.onvivals.app.ai.tts.AbstractTtsService;
import org.onvivals.common.utils.FFmpegUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class MinimaxTtsService extends AbstractTtsService {

	private JSONObject ttsConfig;


	private static final Lock lock = new ReentrantLock();

	public MinimaxTtsService(JSONObject config) {
		this.ttsConfig = config;
	}
    public MinimaxTtsService() {
    }

    public static String generateFilePath() {
        lock.lock();
        try {
            String tmpDir = System.getProperty("java.io.tmpdir");
            String uniqueId = IdUtil.getSnowflakeNextIdStr();
            return tmpDir + uniqueId + ".mp3";
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        String key = ttsConfig.getStr("key");
        String model = ttsConfig.getStr("model");
        String voiceId = ttsConfig.getStr("voice_id");
        Integer vol = Convert.toInt(ttsConfig.get("vol"),1);
        Integer speed = Convert.toInt(ttsConfig.get("speed"),1);
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("model",model);
        paramMap.put("text",content);
        paramMap.put("stream",false);
        Map<String,Object> voiceSetting = new HashMap<>();
        voiceSetting.put("speed",speed);
        voiceSetting.put("vol",vol);
        voiceSetting.put("pitch",0);
        voiceSetting.put("voice_id",voiceId);
        paramMap.put("voice_setting",voiceSetting);
        Map<String,Object> audioSetting = new HashMap<>();
        audioSetting.put("sample_rate",16000);
        audioSetting.put("bitrate",32000);
        audioSetting.put("format","mp3");
        paramMap.put("audio_setting",audioSetting);
        JSONObject jsonObject = new JSONObject(paramMap);
        HttpResponse response = HttpUtil.createPost("https://api.minimax.chat/v1/t2a_v2")
                .header("Authorization", "Bearer " + key)
                .body(jsonObject.toString())
                .execute();
        if (response.isOk()) {
            JSONObject result = new JSONObject(response.body());
            String data = result.getJSONObject("data").getStr("audio");
            String filePath = generateFilePath();
            byte[] bytes = HexUtil.decodeHex(data.toCharArray());
			File f = new File(filePath);
            FileUtil.writeBytes(bytes,f);
			String newFilePath = generateFilePath();
			FFmpegUtils.waveMaker(f.getAbsolutePath(), newFilePath);
			f.delete();
			return Optional.of(newFilePath);
        } else {
            log.error("ReechoTtsService error: {}", response.body());
        }
        return Optional.empty();
    }

}
